//
//  RedViewController.m
//  BlockDemo
//
//  Created by UniHan_iMac on 17/3/27.
//  Copyright © 2017年 UniHan_iMac. All rights reserved.
//

#import "RedViewController.h"
#import "YellowViewController.h"
#import "GreenViewController.h"
@interface RedViewController ()

@end

@implementation RedViewController
// 全局变量和静态变量可以在block中直接赋值；局部变量不能在block中直接赋值，需加__block修饰，但是可以获取到局部变量的值。

// self 和 self的属性（@property属性）不能直接在block中使用，会造成循环引用，因此需提前用__weak 或 __block 修饰后再在block中使用。

// block默认存放在栈中，使用copy描述时，会将栈中的block复制一份存放在堆中，这样将来回调block时，block不会被释放掉，造成程序崩溃（app crash）。
- (IBAction)ChangeColor:(id)sender {
    YellowViewController *yellowVC = [[YellowViewController alloc] init];
    yellowVC.yellowViewColor = [UIColor yellowColor];// 正向传值：属性传值
    [self.navigationController pushViewController:yellowVC animated:YES];
    
    UIView *view = _redView;// 防止循环引用
    yellowVC.changeColorBlock = ^(int tag){
        view.backgroundColor = tag == 10 ? [UIColor yellowColor] :[UIColor greenColor];
    };
    // 第二种方法创建block
    _ChangeColors = ^(int tag){};
}
- (IBAction)ChangeGreenColor:(id)sender {
    GreenViewController *greenVC = [[GreenViewController alloc] init];
    greenVC.greenViewColor = [UIColor greenColor];// 正向传值：属性传值
    [self.navigationController pushViewController:greenVC animated:YES];
    
    __weak typeof(self) weakSelf = self;// 防止循环引用
    greenVC.changeColorBlock = ^(int tag)
    {
        weakSelf.redView.backgroundColor = tag == 20 ? [UIColor greenColor] : [UIColor redColor];
    };
}

- (void)viewDidLoad {
    [super viewDidLoad];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
